//
//  StatusListViewModel.swift
//  个人微博
//
//  Created by guo3920591 on 16/4/23.
//  Copyright © 2016年 guo3920591. All rights reserved.
//

import Foundation

import SDWebImage
/// 微博列表视图模型 - 负责加载网络 和本地缓存
//
class StatusListViewModel{
    
    ///私有属性 微博视图模型
     lazy  var statusList = [StatusViewModel]()
    
    
    func cleanup(){
        
        statusList.removeAll()
    }
    
    
    func loadStatusList(isPullup: Bool,finished:(isSuccessed: Bool) ->()) {
        //下拉刷新索引 - 取数组第一项 id
        
        let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
        
        //上拉刷新索引 - 取数组最后一项
        
        let max_id  =  !isPullup ? 0 : (statusList.last?.status.id ?? 0)
        
        //加载微博数据
        
        NetworkTools.sharedTools.loadStatus(since_id,max_id: max_id) { (result) -> () in
            
            
            
            guard let array = result?["statuses"] as? [[String:AnyObject]] else{
                
                finished(isSuccessed: false)
                
                return
            }
            
            
            var arrM = [StatusViewModel]()
            
            for dict in array{
                
                arrM.append(StatusViewModel(status: StatusModel.yy_modelWithDictionary(dict)!))
            }
            
            
            
            print("本次刷新条数\(arrM.count)")
            
            //刷新数据
            //如果是上拉刷新 将刷新的数组放在后面
            
            if max_id>0{
                
                self.statusList += arrM
                
            }else{
                self.statusList = arrM + self.statusList
            }
           
            //在成功回调之前缓存单张图片 完成之后再成功回调
            
            self.cacheSingleWebImage(arrM,finished: finished)
            
           
            
            
        }
        
    }
    
     /// 缓存单张图片 本次网络请求的微博模型数据
    ///应该在缓存单张图片之后，更新视图模型的配图视图大小，在王成回调刷新UI
    private func cacheSingleWebImage(arrM: [StatusViewModel],finished: (isSuccessed: Bool) -> ()){
        
        //1创建调度组
        let group = dispatch_group_create()
        
        var dataLength = 0
        
        
        for viewModel  in arrM {
            //如果图片的数据不为1者继续
            if viewModel.pictureUrl?.count != 1{
                
                continue
            }
            
           //2一定是单张图片 获取url
            guard let urlString = viewModel.pictureUrl?[0].thumbnail_pic,url = NSURL(string: urlString)
 else {
               
                continue
            }
            
            print(viewModel.pictureUrl)
            
           //下载图像，调用SDwebimage
            
         //block之前入组 
            dispatch_group_enter(group)
           SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [],
               progress: nil,
               completed: { (image, _, _, _, _) -> Void in
                
                //判断图像是否下载成功
                
                if let image = image,data = UIImagePNGRepresentation(image) {
                    
                  //累加数据长度
                    dataLength += data.length
                    
                    //更新模型对应的视图大小
                    viewModel.updataSinglePictureViewSize()
                   
                }
                //3出组
                dispatch_group_leave(group)
                
                
           })
            
            
        }
        
        //监听下载完成
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            print("单张图片缓存完成\(dataLength / 1024)k")
            
            
            
            //执行完成回调
            
            finished(isSuccessed: true)
            
        }
        
        
    }
    
    
}